
package cn.zlg.common.springmvc.validate.constraintsvalidator;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.annotation.Resource;
import javax.sql.DataSource;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

import cn.zlg.common.springmvc.validate.constraints.UniqueInDB;

/**
 * Validate that the object is not <code>null</code>.
 *
 * @author Emmanuel Bernard
 */
public class UniqueInDBValidator implements ConstraintValidator<UniqueInDB, Object> {
    UniqueInDB parameters;
    @Resource
    DataSource dataSource;

    public void initialize(UniqueInDB parameters) {
        this.parameters = parameters;
    }

    public boolean isValid(Object object, ConstraintValidatorContext constraintValidatorContext) {
        if (object == null) {
            return true;
        }
        try {
            Connection connection = dataSource.getConnection();
            PreparedStatement statement = connection.prepareStatement(
                    "select count(*) from " + parameters.table() + " where " + parameters.column() + "=?");
            statement.setObject(1, object);
            ResultSet set = statement.executeQuery();
            set.first();
            boolean valid = set.getInt(1) == 0;
            statement.close();
            return valid;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return false;
    }
}